class UsersController < ApplicationController
  # Be sure to include AuthenticationSystem in Application Controller instead
  # include AuthenticatedSystem

  before_filter :admin_required
  before_filter :find_user, :only => [:edit, :update, :destroy]

  layout 'admin'

  def index
    @users = User.find(:all, :include => [:team], :order => :display_order)
  end

  # render new.rhtml
  def new
    @user = User.new
    @users = User.find(:all, :order => :display_order)
  end
 
  def create
    @user = User.new(params[:user])
    success = @user && @user.save
    if success && @user.errors.empty?
      redirect_to users_path
      flash[:notice] = "#{@user.name}を登録しました。"
    else
      @users = User.find(:all, :order => :display_order)
      render :action => 'new'
    end
  end

  def destroy
    if @user.only_admin?
      flash[:error] = "管理者は最低1人必要です。"
    else
      begin
        User.transaction do
          task_ids = @user.periods.map {|period| period.task_id }.uniq
          remain_tasks = Task.find(:all, {
            :conditions => [
              "tasks.id IN (?) AND periods.user_id != ?",
              task_ids, @user.id
            ],
            :include => :periods
          })
          Task.delete(task_ids - remain_tasks.map(&:id))
          Period.delete_all(:user_id => @user.id)
          remain_tasks.each do |task|
            task.begin_at = task.periods.find(:first, :order => 'begin_at').begin_at
            task.end_at = task.periods.find(:first, :order => 'end_at desc').end_at
            task.save!
          end
          User.delete(@user.id)
          flash[:notice] = "#{@user.name}を削除しました。"
        end
      rescue
        flash[:error] = "#{@user.name}の削除に失敗しました。"
      end
    end
    redirect_to users_path
  end

  def edit
    @teams = Team.find(:all)
    @users = User.find(:all, :order => :display_order) - [@user]
  end

  def update
    if @user.admin? && params[:user].has_key?(:permission) && params[:user][:permission] != 'admin' && !User.multiple_admins_exists?
      @user.errors.add(:permission, '管理者は最低1人必要です。')
    end
    @user.attributes = params[:user]

    begin
      raise unless @user.errors.empty?
      User.transaction do
        @user.save!
      end
      flash[:notice] = "#{@user.name}の変更を保存しました。"
      redirect_to users_path
    rescue
      @teams = Team.find(:all)
      @users = User.find(:all, :order => :display_order) - [@user]
      render :action => 'edit'
    end
  end

  protected
  def find_user
    begin
      @user = User.find(params[:id], :include => :team)
    rescue ActiveRecord::RecordNotFound
      redirect_to users_url
    end
  end

end
